package com.summer.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.summer.core.util.HashCrypt;
import com.summer.dingding.model.DingDingUser;
import com.summer.user.exception.ConfigNotFoundException;
import com.summer.user.exception.UserNotFoundException;
import com.summer.user.model.User;
import com.summer.user.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	HibernateTemplate ht;
	
	@Resource
	private UserBO userBO;
	
	@Override
	@Transactional(readOnly = false ,rollbackFor = Exception.class)
	public void saveUser(User user) {
		// TODO Auto-generated method stub
		ht.save(user);
		
	}
	
	@Override
	@Transactional(readOnly = false ,rollbackFor = Exception.class)
	public List<User> listUsers() {
		
		List<User> userList = new ArrayList<User>();
		
		userList = ht.find("from User u");
		return userList;
	}
	
	public String getMessage() {
		
		System.out.println("come in");
		
		return "success";
	}
	
	@Override
	public boolean verifyOldPassword(String userId, String oldPassword)
			throws UserNotFoundException {
		User user = ht.get(User.class, userId);
		if (user == null) {
			throw new UserNotFoundException("id:" + userId);
		}
		//用户密码是通过加密保存的
		if (user.getPassword().equals(HashCrypt.getDigestHash(oldPassword))) {
			return true;
		}
		return false;
	}
	
	/**
	 * 修改登录密码
	 * 密码通过sha加密
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void modifyPassword(String userId, String newPassword)
			throws UserNotFoundException {
		User user = ht.get(User.class, userId);
		if (user == null) {
			throw new UserNotFoundException("id:" + userId);
		}
		//用户密码通过sha加密保存
		user.setPassword(HashCrypt.getDigestHash(newPassword));
		//用户解锁
//		user.setStatus(UserConstants.UserStatus.ENABLE);
		
		userBO.update(user);
	}
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void changeUserStatus(String userId, String status)
			throws UserNotFoundException, ConfigNotFoundException {
		User user = ht.get(User.class, userId);
		if (user == null) {
			throw new UserNotFoundException("userId:" + userId);
		}
		user.setStatus(status);
		userBO.update(user);
	}
	
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void changeBindDingDingStatus(String userId, String status)
			throws UserNotFoundException, ConfigNotFoundException {
		User user = ht.get(User.class, userId);
		if (user == null) {
			throw new UserNotFoundException("userId:" + userId);
		}
		user.getDuser().setBindStatus(status);
		userBO.update(user);
	}
}
